package com.study.rocket.transaction.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * @author mjy
 * @date 2021/12/14
 * @description
 */
public class Consumer {

    public static void main(String[] args) throws Exception {
        //创建消费者consumer,制定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("transactionGroup");
        //指定nameServer地址
        consumer.setNamesrvAddr("127.0.0.1:9876");
        //订阅主题
        consumer.subscribe("transactionTopic", "*");
        //指定消费则者消费模式(此出修改为广播模式)
        consumer.setMessageModel(MessageModel.BROADCASTING);
        //指定消息的监听者
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            //接收消息的方法
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt msg : msgs) {
                    System.out.println(new String(msg.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();
    }
}
